//
//  WOPrototypeAppDelegate.m
//  WOPrototype
//
//  Created by Olof Millberg on 2010-04-14.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "WOPrototypeAppDelegate.h"
#import "WOHomeViewController.h"
#import "WOListViewController.h"
#import "WOTabBarController.h"

#import <AddressBook/AddressBook.h>

@implementation WOPrototypeAppDelegate

@synthesize window;
@synthesize sqlReader;
@synthesize navigationController;
@synthesize currentUser;
@synthesize users;
@synthesize selectedWorkOrder;

#pragma mark Initialization Methods

/* The application is launched */
- (void)applicationDidFinishLaunching:(UIApplication *)application 
{
	// Override point for customization after application launch
	WOHomeViewController *woHomeVC = [[WOHomeViewController alloc] init];
	navigationController = [[UINavigationController alloc] initWithRootViewController:woHomeVC];
	
	WOListViewController *listVC = [[WOListViewController alloc] init];
	[navigationController pushViewController:listVC animated:NO];
	
	//Add people to address book.
	sqlReader = [[SQLiteReader alloc] initWithDatabase:@"trawoh.sql"];
	NSMutableArray *allPeople = [[self.sqlReader getAddressBookEntries] retain];
	[self addPeopleToAddressBook:allPeople];
	
	//Save possible users.
	users = allPeople;
	
	// Get previous user
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *socialID = [defaults stringForKey:@"currentUser"];
	if (socialID)
		self.currentUser = [sqlReader getPersonBySocialID:socialID];
	else
		// If no user was found pick the first one in the list
		self.currentUser = [users objectAtIndex:0];
	
	//Set selected work order to nil by default.
	selectedWorkOrder = nil;
	
	// Get the work order we were on last time.
	NSInteger currentWorkOrder = [defaults integerForKey:@"currentWorkOrder"];
	
	if (currentWorkOrder != 0)
	{
		selectedWorkOrder = [sqlReader getWorkOrderByWorkID:currentWorkOrder];
		WOTabBarController *tabBarController = [[[WOTabBarController alloc] initWithWorkOrder:selectedWorkOrder] autorelease];
		tabBarController.selectedIndex = [defaults integerForKey:@"currentTab"];
		[navigationController pushViewController:tabBarController animated:NO];
	}
	
	[sqlReader release];
	[window addSubview:navigationController.view];
    [window makeKeyAndVisible];
	[woHomeVC release];
	[listVC release];
}

/* The application terminates */
- (void) applicationWillTerminate:(UIApplication *)application
{
	if(selectedWorkOrder != nil)
	{
		sqlReader = [[SQLiteReader alloc] initWithDatabase:@"trawoh.sql"];
		[sqlReader updateWorkOrder:selectedWorkOrder];
		[sqlReader release];
	}
}

/* Deallocate stuff */
- (void) dealloc {
	[navigationController release];
    [window release];
	[users release];
	[selectedWorkOrder release];
	[currentUser release];
    [super dealloc];
}

#pragma mark -

#pragma mark Other Methods

- (void) setCurrentUser:(WOPerson *)aPerson
{
	[currentUser release];
	currentUser = [aPerson retain];
	[[NSUserDefaults standardUserDefaults] setObject:currentUser.socialID forKey:@"currentUser"];
}

#pragma mark -

#pragma mark Addressbook Related Methods

- (void) addPeopleToAddressBook:(NSMutableArray *) allPeople
{
	//Create reference to address book and new entry
	ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
	ABRecordRef newRecord;
	
	for(WOPerson *currentPerson in allPeople) 
	{
		newRecord = ABPersonCreate();
		CFErrorRef  error= NULL;
		
		CFStringRef socialID = (CFStringRef)currentPerson.socialID;
		CFStringRef firstName = (CFStringRef)currentPerson.firstName;
		CFStringRef lastName = (CFStringRef)currentPerson.lastName;
		CFStringRef email = (CFStringRef)currentPerson.email;
		CFStringRef phone = (CFStringRef)currentPerson.phone;
		
		//Set note with social ID
		ABRecordSetValue(newRecord, kABPersonNoteProperty, socialID, &error); 
		
		//Set first and last name.
		ABRecordSetValue(newRecord, kABPersonFirstNameProperty, firstName, &error); 
		ABRecordSetValue(newRecord, kABPersonLastNameProperty, lastName, &error);
			
		//Create, set and release mail addresses.
		ABMutableMultiValueRef emails = ABMultiValueCreateMutable(kABMultiStringPropertyType);
		ABMultiValueAddValueAndLabel(emails, email, kABWorkLabel, NULL);
		ABRecordSetValue(newRecord, kABPersonEmailProperty, emails, &error);
		CFRelease(emails);
		
		//Create, set and release phone numbers.
		ABMutableMultiValueRef phones = ABMultiValueCreateMutable(kABMultiStringPropertyType);
		ABMultiValueAddValueAndLabel(phones, phone, kABWorkLabel, NULL);
		ABRecordSetValue(newRecord, kABPersonPhoneProperty, phones, &error);
		CFRelease(phones);
		
		//Add to work group.
		CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups (iPhoneAddressBook);
		for(int i = 0; i < [(NSArray *)allGroups count]; i++)
		{
			ABRecordRef currentGroup = [(NSArray *)allGroups objectAtIndex:i];
			NSString *groupName = (NSString *)ABRecordCopyValue(currentGroup, kABGroupNameProperty);
			if([groupName isEqualToString:@"Work"])
			{
				ABGroupAddMember(currentGroup, newRecord, &error);
				break;
			}
			[groupName release];
		}
		if(allGroups != NULL)
			CFRelease(allGroups);
		
		if (error != NULL) NSLog(@"Error while creating...");
		
		//Check for duplicates
		BOOL exists = NO;
		CFArrayRef addedContacts = ABAddressBookCopyArrayOfAllPeople(iPhoneAddressBook);
		for(int i = 0; i < [(NSArray *)addedContacts count]; i++)
		{
			if([self compareAddressBookContact:newRecord with:[(NSArray *)addedContacts objectAtIndex:i]])
			{
				exists = YES;
				break;
			}
		}
		
		[(NSArray *) addedContacts release];
		
		//Already contacts won't be added again.
		if(!exists)
		{
			BOOL isAdded = ABAddressBookAddRecord (iPhoneAddressBook, newRecord, &error);
			
			if(isAdded) NSLog(@"added..");
			if (error != NULL) NSLog(@"ABAddressBookAddRecord %@", error);
			
			error = NULL;
			BOOL isSaved = ABAddressBookSave(iPhoneAddressBook,&error);
			
			if(isSaved) NSLog(@"saved..");
			
			if (error != NULL) NSLog(@"ABAddressBookSave %@", error);
		}
		if(newRecord != NULL)
			CFRelease(newRecord);
	}
	//Release references new entry.
	if(iPhoneAddressBook != NULL)
		CFRelease(iPhoneAddressBook);
}

/* Compares two contacts in the addressbook */
- (BOOL) compareAddressBookContact:(ABRecordRef) refA with:(ABRecordRef) refB
{		
	NSString *refASocialID = (NSString *) ABRecordCopyValue(refA, kABPersonNoteProperty); 
	NSString *refBSocialID = (NSString *) ABRecordCopyValue(refB, kABPersonNoteProperty);
	
	[refASocialID autorelease];
	[refBSocialID autorelease];
	
	if(refBSocialID == nil)
		return NO;
	else
		return [refASocialID isEqualToString:refBSocialID];
}

#pragma mark -

@end